<?php
namespace app\api\command;
/**
 * Created by PhpStorm.
 * User: xpz
 * Date: 2021/6/4
 * Time: 11:19
 */
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Exception;

use think\Config;
use think\Db;
use app\common\model\Article;

class BackTask extends Command
{
    private $userModel;
    private $chengyuModel;
    private $poetModel;
    private $poetryModel;
    private $chengyuEasyGameModel;
    protected function configure()
    {
        $this->setName('backtask') //定义命令的名字
        ->addArgument('method');
    }

    //php think backtask reset_score
    protected function execute(Input $input, Output $output)
    {

        $method = $input->getArgument('method');

        if ($method == 'reset_score') {

        } else if ($method == 'chengyusort') {

        } else if ($method == 'temp'){
            $this->donwImage();
        } else {
            echo "参数错误！参数列表：reset_score|del\n";
        }
    }

    private function donwImage(){
        $articleModel = new Article();
        $rs = collection($articleModel->where(['is_down'=>1,'source'=>2,'status'=>1])->limit(30)->select())->toArray();
        // echo $articleModel->getLastSql();exit;
        if(!empty($rs)){
            foreach($rs as $k=>$v){
                $updateArr = [
                  'is_down' => 2,
                ];
                $imageArr = json_decode($v['images'],true);
                $donwImageArr = $this->_downImg($imageArr,$v['id']);
//                print_r($donwImageArr);
                if(!empty($donwImageArr['target'])){
                    $updateArr['image'] = $donwImageArr['target'][0];
                    $updateArr['images'] = json_encode($donwImageArr['target']);
                    $articleModel->where(['id'=>$v['id']])->update($updateArr);
                } else {
                    echo "图片为空！\r\n";
                }

            }
        }
    }



    private function _downImg($imgArr,$id){
        if(!empty($imgArr)){
            $imgNewArr = [];
            $rootFileDir = Config::get('upload_img_path');
            $fileDir = "/uploads/article/images/" . date("Ymd", time()) . "/"; //图片存放路径
            $imgPath = $_SERVER['DOCUMENT_ROOT'] . $rootFileDir.$fileDir; //图片存放路径
            foreach($imgArr as $k=>$v){
                $imgName = $id.'_'.md5($v) . '.jpg'; //重命名图片名字
                $imgRs = $this->_getImage($v, $imgPath, $imgName); //下载图片到本地
                if($imgRs['code'] == 0){
                    $imgNewArr[] = $fileDir.$imgName;
                }
            }
        }
        return ['source'=>$imgArr,'target'=>$imgNewArr];
    }


    /*
     * 功能：php完美实现下载远程图片保存到本地 ，当前仅支持单个图片下载
     * 参数：文件url,保存文件目录,保存文件名称，使用的下载方式
     * 当保存文件名称为空时则使用远程文件原来的名称
     */

    private function _getImage($url, $save_dir = '', $filename = '', $type = 0) {
//        echo $filename;exit;
        if (trim($url) == '') {
            return array('code' => 1, 'error' => '文件url不合法');
        }

        if($url){

        }

        if (trim($save_dir) == '') {
            $save_dir = './';
        }
        if (trim($filename) == '') {//保存文件名
            $ext = strrchr($url, '.');
            if ($ext != '.gif' && $ext != '.jpg' && $ext != '.png') {
                return array('code' => 3, 'error' => '文件类型不合法');
            }
            $filename = substr($url, strripos($url, "/") + 1);
        }

        if (0 !== strrpos($save_dir, '/')) {
            $save_dir.='/';
        }
        //创建保存目录
        if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {
            return array('code' => 5, 'error' => '创建文件失败');
        }
        //获取远程文件所采用的方法
        if ($type) {
            $ch = curl_init();
            $timeout = 5;
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            $img = curl_exec($ch);
            curl_close($ch);
        } else {
            ob_start();
            readfile($url);
            $img = ob_get_contents();
            ob_end_clean();
        }
        $size = strlen($img);


        //文件大小
//        echo $save_dir.$filename;exit;
        $fp2 = @fopen($save_dir . $filename, 'a');
        fwrite($fp2, $img);
        fclose($fp2);
//        print_r($filename);exit;
        unset($img, $url);
//        if($size > 1048576){ //大于1M则删除
//            unlink($save_dir.$filename);
//        }
        return array('code' => 0, 'error' => "文件" . $filename . "保存成功");
    }




}